package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.Cache;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName: sky-take-out
 * @Package: com.sky.service.impl
 * @ClassName: DishServiceImpl
 * @Author: 王加其
 * @Date: 2023/4/17 13:14
 * @Version: 1.0
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional//开启事务管理，涉及多表操作
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        if (dishDTO.getStatus() == null){
            dish.setStatus(StatusConstant.ENABLE);
        }
        //向菜品表添加一条数据
        dishMapper.save(dish);

        //向口味表添加n条数据
        List<DishFlavor> dtoFlavors = dishDTO.getFlavors();
        //前端提交过来的有口味的数据才添加
        if (dtoFlavors != null && dtoFlavors.size()>0){
            dtoFlavors.forEach(f -> f.setDishId(dish.getId()));
            dishFlavorMapper.batchSave(dtoFlavors);
        }
        //5 clear cache
        String cacheKey = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(cacheKey);
    }


    @Override
    @Cache(group = "dishpage",key="#dto.page,#dto.name,#dto.categoryId,#dto.status")
    public PageResult pageQuery(DishPageQueryDTO dto) {
        //1、PageHelper设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //2、调用mapper进行分页条件查询
        Page<DishVO> page = this.dishMapper.pageQuery(dto);

        //3、封装PageResult并返回
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断菜品是否起售，起售中的菜品不能删除
        Integer count = this.dishMapper.CountStatusByIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断是否有套菜关联，被套餐关联的菜品不能删除
        count = this.setmealMapper.countByDishId(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //一次删除一个菜品，批量也行
        this.dishMapper.batchDelete(ids);

        //删除菜品后，关联的口味数据也需要删除
        this.dishFlavorMapper.batchDelete(ids);

        //5 clear cache
        final Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlaovr(Long id) {
        DishVO dishVO = dishMapper.getByIdWithFlaovr(id);
        return dishVO;
    }

    /**
     * 根据id修改菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //将dishDTO中有关dish的数据拷贝到dish中
        BeanUtils.copyProperties(dishDTO,dish);
        //先修改菜品的基本信息
        this.dishMapper.update(dish);
        //删除原有的口味数据
        List ids = new ArrayList<>();
        ids.add(dishDTO.getId());
        this.dishFlavorMapper.batchDelete(ids);
        //重新插入口味数据
        List<DishFlavor> Flavors = dishDTO.getFlavors();
        if (Flavors!=null && Flavors.size()>0) {
            Flavors.forEach(f -> f.setDishId(dish.getId()));
        }
        dishFlavorMapper.batchSave(Flavors);
        //4 clear cache
        final DishVO dishVO = dishMapper.getByIdWithFlaovr(dishDTO.getId());
        String cacheKey = "dish_" + dishVO.getCategoryId();
        redisTemplate.delete(cacheKey);
        cacheKey = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(cacheKey);
    }

    /**
     * 起售，停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        this.dishMapper.update(dish);
        //5 clear cache
        final Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据类型id和菜品名称查询
     * @param categoryId
     * @param name
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId, String name) {

        return dishMapper.list(categoryId,name);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        String cacheKey = "dish_" + dish.getCategoryId();
        //query cache dish by getCategoryId
        List<DishVO> dishVOS = (List<DishVO>)redisTemplate.opsForValue().get(cacheKey);
        if(ObjectUtils.isNotEmpty(dishVOS)){
            return dishVOS;
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<DishVO> list = dishMapper.listWithFlavor(dish);
        redisTemplate.opsForValue().set(cacheKey,list);
        return list;
    }
}
